import React, { Component, useRef, useState } from 'react'
import { SearchOutlined, CloseOutlined } from '@ant-design/icons';
import {
  Form, Input, Space, Button, DatePicker, Tabs, Select, Steps, Modal, notification, Affix, Row, Col, List,
  Tag
} from 'antd'
import _ from 'lodash'
import axios from 'axios';
import TheButton from '@/components/TheButton'
import TheTable from '@/components/TheTable'
import TheImage from '@/components/TheImage'
import ThePagination from '@/components/ThePagination'
import TheDialog from '@/components/TheDialog'
import {
  apiShopOrderInfoPage,
  apiExpressageList,
  apiDeliverymanPage,
  apiSendOrders,
  apiExportLibraryOutReport,
  apiShopOrderDetail,
  apiOrderNoticeStatistic,
  apiOrderNoticeDel,
  apiPostMergeOrderDetail,
  apiGetShopOrderInfoPage,
  apiGetShopOrderInfoList
} from '@/request/orderManagement'
import { apiIdentificationCodeAdd } from '@/request/common'

import { apiGetTSysDictionariesList } from '@/request/Dictionaries'
import { getDateTime3, getDateTime2 } from '@/utils/getDate'
import { exportTable, exportSheetTable } from '@/utils/exportTable.js'
import { printLogo, mergePrints, toPrintTool, printQrCode } from '@/utils/toPrint.js'
import SendGoods from '../MallOrder/components/sendGoods'
import store from "@/store/store"
import moment from 'moment'
import './style/style.less'

const { RangePicker } = DatePicker
const { TabPane } = Tabs
const { Step } = Steps
const { confirm } = Modal

const SearchHeader = ({ getValue, educeTable, orderState }) => {
  const formRef = useRef()
  const searchValue = store.getState().searchValue || {}
  const [orderCode, setOrderCode] = useState(searchValue.orderCode)
  const onFinish = (values) => {
    if (values.time && values.time.length) {
      values.createTimeStart = getDateTime3(values.time[0]) + ' 00:00:00'
      values.createTimeEnd = getDateTime3(values.time[1]) + ' 23:59:59'
    }
    delete (values.time)
    _.forIn(values, (v, k) => {
      if (!v) {
        delete (values[k])
      }
    })
    getValue(values)
  }
  const reset = () => {
    formRef.current.setFieldsValue({
      orderCode: '',
      activityTypeCode: null,
      time: []
    })
    getValue({})
  }
  const tableExport = () => {
    educeTable({ type: 'orderList', option: formRef.current.getFieldValue() })
  }
  const saleOutExport = () => {
    educeTable({ type: 'saleOut', option: formRef.current.getFieldValue() })

  }
  const changeParams = (e, key) => {
    setOrderCode(e.target.value)
  }
  return (
    <Form ref={formRef} onFinish={onFinish} layout="inline">
      <Form.Item name="orderCode">
        <Input placeholder='请输入订单号' defaultValue={orderCode}
          onChange={(e) => changeParams(e, 'orderCode')} suffix={<SearchOutlined />} />
      </Form.Item>
      <Form.Item name="activityTypeCode" >
        <Select allowClear options={[
          {
            value: '0',
            label: '普通订单'
          },
          {
            value: '1',
            label: '砍价订单'
          },
          {
            value: '2',
            label: '拼团订单'
          },
          {
            value: '3',
            label: '奖品订单'
          }
        ]} placeholder={"请选择订单类型"} style={{ width: "160px" }} />
      </Form.Item>
      <Form.Item name="time" label="下单时间">
        <RangePicker format={'YYYY/MM/DD'} defaultValue={searchValue.hasOwnProperty('createTimeStart') ? [moment(searchValue.createTimeStart, 'YYYY/MM/DD'), moment(searchValue.createTimeEnd, 'YYYY/MM/DD')] : []} />
      </Form.Item>
      <Form.Item>
        <Space>
          <Button htmlType="submit" type="primary">搜索</Button>
          <Button onClick={reset}>重置</Button>
          {
            orderState == 4 ? <TheButton type="default" size='middle' hasPermi={['order:MallOrderKeeper:exportOrder']} onClick={tableExport}>订单导出</TheButton> : null
          }
          {
            orderState == 4 ? <TheButton type="default" size='middle' hasPermi={['order:MallOrderKeeper:sales']} onClick={saleOutExport}>销售出库单导出</TheButton> : null
          }
        </Space>
      </Form.Item>
    </Form>
  );
};

export default class MallOrder extends Component {
  constructor() {
    super()
    this.mergeformRef = React.createRef()
    this.logisticsRef = React.createRef()
    this.sendGoodsRef = React.createRef()
    this.state = {
      noticeTimer: null,
      voiceOn: false,
      columns: [
        {
          title: '订单编号',
          dataIndex: 'orderCode',
          key: 'orderCode',
          render: (text, record) => {
            return <span>
              {text}&nbsp;&nbsp;&nbsp;
              {record.otherDelivery === 1 ? <Tag color="red">代发货</Tag> : ''}
            </span>
          },
        },
        {
          title: '买家昵称',
          dataIndex: 'buyMemberName',
          key: 'buyMemberName'
        },
        {
          title: '自配送单号',
          dataIndex: 'deliveryCode',
          key: 'deliveryCode'
        },
        {
          title: '收货人',
          dataIndex: 'memberName',
          key: 'memberName'
        },
        {
          title: '联系方式',
          dataIndex: 'memberPhone',
          key: 'memberPhone'
        },
        {
          title: '收货地址',
          dataIndex: 'memberAddress',
          key: 'memberAddress'
        },
        // {
        //   title: '订单金额（元）',
        //   dataIndex: 'orderTotalPrice',
        //   key: 'orderTotalPrice',
        //   render: (text) => {
        //     return <React.$Price price={text} />
        //   }
        // },
        // {
        //   title: '实付金额（元）',
        //   dataIndex: 'orderPayPrice',
        //   key: 'orderPayPrice',
        //   render: (text) => {
        //     return <React.$Price price={text} />
        //   }
        // },
        {
          title: '订单时间',
          dataIndex: 'createTime',
          key: 'createTime'
        },
        {
          title: '订单状态',
          dataIndex: 'orderState',
          key: 'orderState',
          render: (text) => {
            let label = ""
            switch (parseInt(text)) {
              case 3:
                label = "待付款";
                break;
              case 4:
                label = "待发货";
                break;
              case 5:
                label = "待收货";
                break;
              case 9:
                label = "交易成功";
                break;
              case 0:
                label = "交易关闭";
                break;
            }
            return label;
          }
        },
        {
          title: '发货时间',
          dataIndex: 'goodsGoTime',
          key: 'goodsGoTime'
        },
        // {
        //   title: '操作',
        //   fixed: 'right',
        //   render: (text, record) => {
        //     return <>
        //       {
        //         parseInt(record.orderState) === 5 &&
        //         <TheButton hasPermi={['order:mallOrderKeeper:reassign']} onClick={() => this.reassignDeliverymanDialog(record.shopOrderId)}>{record.deliveryCode ? "修改配送员" : "修改快递"}</TheButton>
        //       }
        //       <TheButton hasPermi={['order:MallOrderKeeper:view']} onClick={() => this.props.history.push({ pathname: `/order/mallOrder/details/${record.shopOrderId}/keeper` })}>查看订单</TheButton>
        //       {parseInt(record.orderState) === 5 && <TheButton hasPermi={['order:MallOrderKeeper:logisticsView']} onClick={() => this.onLogistics(record)}>查看物流</TheButton>}
        //       {
        //         parseInt(record.orderState) === 4 && record.salesReturnStatus === 1 && '退款中'
        //       }
        //       {
        //         parseInt(record.orderState) === 4 && record.salesReturnStatus !== 1 && parseInt(record.orderState) === 4 && record.salesReturnStatus !== 1 &&
        //         <TheButton hasPermi={['order:MallOrderKeeper:send']} onClick={() => this.openDialog(record.shopOrderId)}>
        //           {
        //             record.otherDelivery == 1 ? '代发货' : '发货'
        //           }
        //         </TheButton>
        //       }
        //       {
        //         parseInt(record.orderState) === 4 && record.salesReturnStatus !== 1 && record.activityTypeCode === 1 && <TheButton hasPermi={['order:mallOrderkeeper:mergesend']} onClick={() => this.mergeDialog({ memberId: record.memberId, buyMemberName: record.buyMemberName, memberName: record.memberName, memberPhone: record.memberPhone, memberAddress: record.memberAddress })}>合并发货</TheButton>
        //       }
        //     </>
        //   }
        // }
      ],
      columns4: [
        {
          title: '订单编号',
          dataIndex: 'orderCode',
          key: 'orderCode',
          render: (text, record) => {
            return <span>
              {text}&nbsp;&nbsp;&nbsp;
              {record.otherDelivery === 1 ? <Tag color="red">代发货</Tag> : ''}
            </span>
          },
        },

        {
          title: '用户id',
          dataIndex: 'memberId',
          key: 'memberId'
        },
        {
          title: '买家昵称',
          dataIndex: 'buyMemberName',
          key: 'buyMemberName'
        },
        {
          title: '订单金额',
          dataIndex: 'orderTotalPrice',
          key: 'orderTotalPrice', render: (text) => {

            return (text / 100).toFixed(2);
          }
        },
        {
          title: '实付金额',
          dataIndex: 'orderPayPrice',
          key: 'orderPayPrice',
          render: (text) => {

            return (text / 100).toFixed(2);
          }
        },

        {
          title: '收货人',
          dataIndex: 'memberName',
          key: 'memberName'
        },
        {
          title: '联系方式',
          dataIndex: 'memberPhone',
          key: 'memberPhone'
        },
        {
          title: '收货地址',
          dataIndex: 'memberAddress',
          key: 'memberAddress'
        },
        {
          title: '支付方式',
          dataIndex: 'payWay',
          key: 'payWay',
          render: (text, record) => {
            return text === "Alipay" ? "支付宝" : (text === "WeChat" ? "微信" : "银行卡")
          }
        },
        // {
        //   title: '实付金额（元）',
        //   dataIndex: 'orderPayPrice',
        //   key: 'orderPayPrice',
        //   render: (text) => {
        //     return <React.$Price price={text} />
        //   }
        // },
        {
          title: '订单时间',
          dataIndex: 'createTime',
          key: 'createTime'
        },
        {
          title: '订单状态',
          dataIndex: 'orderState',
          key: 'orderState',
          render: (text) => {
            let label = ""
            switch (parseInt(text)) {
              case 3:
                label = "待付款";
                break;
              case 4:
                label = "待发货";
                break;
              case 5:
                label = "待收货";
                break;
              case 9:
                label = "交易成功";
                break;
              case 0:
                label = "交易关闭";
                break;
            }
            return label;
          }
        },
        {
          title: '支付时间',
          dataIndex: 'payTime',
          key: 'payTime'
        },
        // {
        //   title: '发货时间',
        //   dataIndex: 'goodsGoTime',
        //   key: 'goodsGoTime'
        // },
        // {
        //   title: '收货时间',
        //   dataIndex: 'goodsArrTime',
        //   key: 'goodsArrTime'
        // },
        // {
        //   title: '操作',
        //   fixed: 'right',
        //   render: (text, record) => {
        //     return <>
        //       <TheButton hasPermi={['order:MallOrderKeeper:view']} onClick={() => this.viewDetail(record)}>查看订单</TheButton>
        //       {parseInt(record.orderState) === 5 && <TheButton hasPermi={['order:MallOrderKeeper:logisticsView']} onClick={() => this.onLogistics(record)}>查看物流</TheButton>}
        //       {
        //         parseInt(record.orderState) === 4 && record.salesReturnStatus === 1 && '退款中'
        //       }
        //       {
        //         parseInt(record.orderState) === 4 && record.salesReturnStatus !== 1 && <TheButton hasPermi={['order:MallOrderKeeper:latesend']} onClick={() => this.openLateDialog(record.shopOrderId)}
        //           disabled={record.delayReason ? true : false} >延迟发货</TheButton>
        //       }
        //       {
        //         parseInt(record.orderState) === 4 && record.salesReturnStatus !== 1 && <TheButton hasPermi={['order:MallOrderKeeper:send']} onClick={() => this.openDialog(record.shopOrderId)}>  {
        //           record.otherDelivery == 1 ? '代发货' : '发货'
        //         }</TheButton>
        //
        //       }
        //       {
        //         parseInt(record.orderState) === 4 && record.salesReturnStatus !== 1 && record.otherDelivery != 1 && <TheButton hasPermi={['order:MallOrderKeeper:mergesend']} onClick={() => this.mergeDialog({ memberId: record.memberId, buyMemberName: record.buyMemberName, memberName: record.memberName, memberPhone: record.memberPhone, memberAddress: record.memberAddress })}>合并发货</TheButton>
        //       }
        //     </>
        //   }
        // }
      ],
      dataSource: [],
      tabData: [
        // {
        //   key: '3',
        //   tab: '待付款'
        // },
        {
          key: '4',
          tab: '待发货'
        },
        {
          key: '5',
          tab: '待收货'
        },
        {
          key: '9',
          tab: '交易成功'
        },
        {
          key: '0',
          tab: '交易关闭'
        },
      ],
      pageData3: {
        pageNo: 1,
        pageSize: 10
      },
      pageData4: {
        pageNo: 1,
        pageSize: 10
      },
      pageData5: {
        pageNo: 1,
        pageSize: 10
      },
      pageData9: {
        pageNo: 1,
        pageSize: 10
      },
      pageData0: {
        pageNo: 1,
        pageSize: 10
      },
      total3: 0,
      total4: 0,
      total5: 0,
      total9: 0,
      total0: 0,
      searchValue: {},
      orderState: "4",
      loading: false,
      options: [],
      lateoptions: [],
      isModalVisible: false,
      latevisible: false,
      mergeColumns: [
        {
          title: '订单时间',
          dataIndex: 'createTime',
          key: 'createTime'
        },
        {
          title: '订单编号',
          dataIndex: 'orderCode',
          key: 'orderCode',
          render: (text, record) => {
            return <TheButton onClick={() => this.shopModal(record.shopOrderId)} >{text}</TheButton>
          }
        },
        {
          title: '订单金额（元）',
          dataIndex: 'orderTotalPrice',
          key: 'orderTotalPrice',
          render: (text) => {
            return <React.$Price price={text} />
          }
        },
        {
          title: '实付金额（元）',
          dataIndex: 'orderPayPrice',
          key: 'orderPayPrice',
          render: (text) => {
            return <React.$Price price={text} />
          }
        },
        // {
        //   title: '商品图片',
        //   dataIndex: 'goodsImage',
        //   key: 'goodsImage',
        //   render: (text, record) => {
        //     return <TheImage src={record.orderDetailList[0].goodsImage} width={80} height={80} />
        //   }
        // },
        // {
        //   title: '商品名称',
        //   dataIndex: 'goodsName',
        //   key: 'goodsName',
        //   render: (text, record) => {
        //     return record.orderDetailList[0].goodsName
        //   }
        // },
        // {
        //   title: '物料ID',
        //   dataIndex: 'materialId',
        //   key: 'materialId',
        //   render: (text, record) => {
        //     return record.orderDetailList[0].materialId
        //   }
        // },
        // {
        //   title: '单价（元）',
        //   dataIndex: 'orderPrice',
        //   key: 'orderPrice',
        //   render: (text, record) => {
        //     return <React.$Price price={record.orderDetailList[0].orderPrice} />
        //   }
        // },
        // {
        //   title: '数量',
        //   dataIndex: 'orderDetailList',
        //   key: 'orderDetailList',
        //   render: (text, record) => {
        //     return record.orderDetailList[0].orderProductCount
        //   }
        // },
        // {
        //   title: '总计（元）',
        //   dataIndex: 'orderPriceTotal',
        //   key: 'orderPriceTotal',
        //   render: (text, record) => {
        //     return <React.$Price price={record.orderDetailList[0].orderPriceTotal} />
        //   }
        // },
      ],
      mergeOrderDataSource: [],
      mergeVisible: false,
      mergeOrder: "",
      orderList: [],
      selectedRows: [],
      selectedRowKeys: [],
      OrderVisible: false,
      orderDetails: [],
      courierOptions: [],
      printLoading: false
    }
  }
  componentWillUnmount() {
    clearInterval(this.state.noticeTimer)
    this.setState({
      noticeTimer: null
    })
  }
  componentDidMount() {
    let searchParams = store.getState().searchValue
    if (searchParams) {
      let { pageNo, pageSize, orderState, searchValue } = searchParams
      this.setState({
        searchValue: {
          ...searchParams
        },
        orderState: orderState ? orderState : '4',
        [`pageData${orderState}`]: {
          pageNo: pageNo, pageSize: pageSize
        }
      }, () => {

        this.getData()
      })
    } else {
      this.getData()

    }
    this.getLateShipmentReason()
    this.getExpressage()
    this.getCourierOptions()
  }
  reassignDeliverymanDialog = async (orderId) => {
    this.sendGoodsRef.current.open(orderId)
  }
  audioControl(type) {
    let message = '哈奇马商城订单待处理'
    let url = "https://tts.baidu.com/text2audio?cuid=baike&lan=ZH&ctp=1&pdt=301&vol=9&rate=32&per=0&tex=" + encodeURI(message);
    // baidu文字转语音
    var voiceContent = new Audio(url);
    voiceContent.src = url;
    voiceContent.play()
  }
  viewDetail(record) {
    this.props.history.push({ pathname: `/order/mallOrder/details/${record.shopOrderId}/keeper` })
  }
  // 按类型获取当前新订单统计
  async getOrderStatistic() {
    let res = await apiOrderNoticeStatistic({ type: 2 })
    if (res.code === 0 && res.data > 0 && this.state.voiceOn) {
      // 消息提示框
      const key = `notification`;
      notification.close('notification')
      const btn = (
        <div>
          <Button type="primary" size="small" style={{ marginRight: 20 }} onClick={() => this.notificationSubmit()}>
            立即处理
          </Button>
          <Button size="small" type="dashed" danger ghost onClick={() => this.close()}>
            延后处理
          </Button>
        </div>
      );
      notification.info({
        message: '新订单提醒',
        description:
          '哈奇马商城订单待处理！',
        btn,
        key,

      });
      this.audioControl()
    }
  }
  mergeDialog = async (values) => {
    console.log(values)
    let params = {
      memberName: values.memberName,
      memberPhone: values.memberPhone,
      memberAddress: values.memberAddress
    }
    let res = await React.$post("/management/shopOrderInfo/getCutOrderList", params)
    if (res.code === 0) {
      res.data = res.data.filter(item => item.otherDelivery != 1)
      this.setState({
        mergeVisible: true,
        mergeOrder: values,
        mergeOrderDataSource: _.flattenDeep(res.data),
      })
    }
  }
  mergeCloseDialog = () => {
    this.setState({
      mergeVisible: false,
      mergeOrder: "",
      mergeOrderDataSource: [],
      orderList: [],
      selectedRows: [],
      selectedRowKeys: []
    })
  }
  mergeSaveDialog = () => {
    if (this.state.orderList.length === 0) {
      React.$message({
        type: "warning",
        content: '请选择要发货的订单'
      })
    } else {
      this.mergeformRef.current.validateFields().then(async (err) => {
        if (err) {
          console.log(this.mergeformRef.current.getFieldsValue());
          let params = {
            orderIds: this.state.orderList.join(','),
            ...err,
          }
          console.log(params);
          let res = await React.$post("/management/shopOrderInfo/sendMergeOrders", params)
          if (res.code === 0) {
            React.$message({
              type: "info",
              content: '合并发货成功'
            })
            this.mergeCloseDialog()
            this.getData()
          }
        }
      })
    }
  }
  onChange = (selectedRowKeys, selectedRows) => {
    console.log(selectedRowKeys, selectedRows);
    this.setState({
      selectedRows: selectedRows,
      selectedRowKeys: selectedRowKeys
    }, () => {
      let rows = this.state.selectedRows.length
      let orders = []
      let ordercheck = []
      for (let i = 0; i < rows; i++) {
        orders.push(selectedRows[i].shopOrderId)
        ordercheck.push(selectedRows[i].orderCode)
      }
      this.setState({
        orderList: orders
      })
    })
  }
  CancelChange = (orderId, Rows) => {
    let { selectedRowKeys, selectedRows } = this.state
    selectedRowKeys = selectedRowKeys.filter(item => item != orderId)
    selectedRows = selectedRows.filter(item => item != Rows)
    console.log(selectedRowKeys, selectedRows);
    this.onChange(selectedRowKeys, selectedRows)
  }
  close = () => {
    notification.close('notification')
  };
  notificationSubmit = async () => {

    let res = await apiOrderNoticeDel({ type: 2 })
    if (res.code == 0) {
      notification.close('notification')
    }
  };
  getLateShipmentReason = async () => {
    let res = await apiGetTSysDictionariesList({ name: "lateShipment" })
    if (res.code === 0 && res.data) {
      let lateoptions = res.data.map(v => {
        return {
          value: v.value,
          label: v.value
        }
      })
      this.setState({ lateoptions })
    }
  }

  getExpressage = async () => {
    let res = await apiExpressageList()
    if (res.code === 0 && res.data) {
      let options = res.data.map(v => {
        return {
          value: v.expressageCompanyCode,
          label: v.expressageCompanyName
        }
      })
      this.setState({ options })
    }
  }

  getData = async () => {
    this.setState({ loading: true })
    const { searchValue, orderState } = this.state
    let params = {
      ...searchValue, ...this.state[`pageData${orderState}`], orderState
    }
    store.dispatch({
      type: 'SaveSearchValues',
      data: {
        ...params
      }
    })
    let res = await apiGetShopOrderInfoPage({ ...params })
    if (res.code === 0 && res.data) {
      this.setState({
        dataSource: res.data,
        [`pageData${orderState}`]: {
          pageNo: res.pageNo,
          pageSize: res.pageSize
        },
        [`total${orderState}`]: res.totalCount
      })
    }
    this.setState({ loading: false })
  }
  pageChange = (pageNo, pageSize) => {
    const { orderState } = this.state
    this.setState({
      [`pageData${orderState}`]: {
        pageNo,
        pageSize
      }
    }, () => {
      this.getData()
    })
  }
  getValue = value => {
    const { orderState } = this.state
    this.setState({
      [`pageData${orderState}`]: {
        pageNo: 1,
        pageSize: 10
      },
      searchValue: value
    }, () => {
      this.getData()
    })
  }
  changeKey = key => {
    this.setState({
      orderState: key
    }, () => {
      this.getData()
      if (key != 4) {
        if (key === 5) {
          this.state.columns.push({
            title: '发货时间',
            dataIndex: 'goodsGoTime',
            key: 'goodsGoTime'
          })
          console.log(this.state.columns);
        }
        clearInterval(this.state.noticeTimer)
        this.setState({
          noticeTimer: null,
          voiceOn: false
        })
      }
    })
  }
  openDialog = async (orderId) => {
    // let that = this
    // // 查询订单是否存在退货商品
    // let hasReturn = await apiShopOrderDetail({ orderId })
    // if (hasReturn.code === 0 && hasReturn.data) {
    //   let flag = hasReturn.data.orderDetailList.filter(item => !['4', '0', null].includes(item.salesStatus))
    //   if (flag.length > 0) {
    //     confirm({
    //       title: '提示', content: <div style={{ color: 'red' }}>订单异常:存在退款商品，是否继续发货？</div>,
    //       onOk() {
    //         that.setState({
    //           visible: true,
    //           orderId
    //         })
    //       },

    //       onCancel() {
    //       },
    //     });
    //     return
    //   }
    //   that.setState({
    //     visible: true,
    //     orderId
    //   })
    // }
    this.sendGoodsRef.current.open(orderId)
  }

  openLateDialog = async (orderId) => {
    let that = this
    // 查询订单是否存在退货商品
    let hasReturn = await apiShopOrderDetail({ orderId })
    if (hasReturn.code === 0 && hasReturn.data) {
      let flag = hasReturn.data.orderDetailList.filter(item => !['4', '0', null].includes(item.salesStatus))
      if (flag.length > 0) {
        confirm({
          title: '提示', content: <div style={{ color: 'red' }}>订单异常:存在退款商品，是否继续延迟发货？</div>,
          onOk() {
            that.setState({
              latevisible: true,
              orderId
            })
          },
          onCancel() {
          },
        });
        return
      }
      that.setState({
        latevisible: true,
        orderId
      })
    }
  }
  latecloseDialog = () => {
    this.setState({
      latevisible: false,
      orderId: ''
    })
  }
  closeDialog = () => {
    this.setState({
      visible: false,
      orderId: ''
    })
  }
  saveLateDialog = async value => {
    const { orderId } = this.state
    let res = await React.$post("/management/shopOrderInfo/setDelayReason", { shopOrderId: orderId, ...value })
    if (res.code === 0) {
      React.$message({
        type: "info",
        content: '延迟发货成功'
      })
      this.latecloseDialog()
      this.getData()
    }
  }
  saveDialog = async value => {
    const { orderId } = this.state
    let courierNo = value.courierNo.trim()
    value.courierNo = courierNo
    let res = await apiSendOrders({ orderId, ...value })
    if (res.code === 0) {
      React.$message({
        type: "info",
        content: '发货成功'
      })
      this.closeDialog()
      this.getData()
    }
  }
  onLogistics = async value => {
    if (value.deliveryCode) {
      this.props.history.push(`/order/mallOrder/details/${value.shopOrderId}/normal`)
    } else {
      // this.logisticsRef.current.onLogistics(value.shopOrderId)
      React.$post(`/management/shopOrderInfo/checkLogistics/${value.shopOrderId}`).then(response => {
        if (response.code === 0 && response.data) {
          let { msg: { context } } = response.data
          context = context ? context.map(v => {
            let time = v.time * 1000
            time = new Date(parseInt(time))
            time = getDateTime2(time)
            return {
              ...v,
              time
            }
          }) : null
          let courierCode = ""
          let options = this.state.options
          for (let i = 0; i < options.length; i++) {
            if (options[i].value === response.data.courierCode) {
              courierCode = options[i].label
            }
          }
          this.setState({
            courierCode,
            courierNo: response.data.courierNo,
            logisticsInformation: context,
            logVisible: true
          })
        } else {
          return React.$message({
            type: 'info',
            content: '暂无物流信息'
          })
        }
      })
    }

  }
  logDialogCancel = () => {
    this.setState({
      logisticsInformation: null,
      logVisible: false
    })
  }
  educeTable = async (e) => {
    // 导出待发货订单
    const { type, option } = e
    if (type === 'orderList') {
      let th_arr = [{ prop: 'orderCode', title: '订单编号' },
      { prop: 'createTime', title: '订单时间' },
      { prop: 'memberId', title: '用户id' },
      { prop: 'buyMemberName', title: '买家昵称' },
      { prop: 'goodsClassifyName', title: '商品分类' },
      { prop: 'goodsName', title: '商品名称' },
      { prop: 'skuAttribute', title: '规格' },
      { prop: 'orderCount', title: '商品数量', valueType: 'number' },
      { prop: 'materialId', title: '物料id' },
      { prop: 'orderPriceTotal', title: '订单金额', valueType: 'number' },
      { prop: 'detailDiscountsPrice', title: '优惠金额', valueType: 'number' },
      { prop: 'detailPayPrice', title: '实付金额', valueType: 'number' },
      { prop: 'orderRemark', title: '用户备注' },
      { prop: 'memberName', title: '收货人' },
      { prop: 'memberPhone', title: '联系方式' },
      { prop: 'memberAddress', title: '收货地址' },
      { prop: 'payTime', title: '支付时间' },
      { prop: 'payWay', title: '支付方式' },
        // { prop: 'goodsGoTime', title: '发货时间' },
        // { prop: 'goodsArrTime', title: '收货时间' }
      ]
      const { searchValue, orderState } = this.state
      let res = await apiGetShopOrderInfoList({ orderState: 4, createTimeEnd: (option.hasOwnProperty('time') && option.time.length > 0) ? getDateTime3(option.time[1]) + ' 23:59:59' : '', createTimeStart: (option.hasOwnProperty('time') && option.time.length > 0) ? getDateTime3(option.time[0]) + ' 00:00:00' : '', orderCode: (option.hasOwnProperty('orderCode') && option.orderCode) ? option.orderCode : '' })
      if (res.code === 0 && res.data) {
        let tb_arr = []
        res.data.forEach(item => {
          if (item.hasOwnProperty('orderDetailList') && item.orderDetailList.length > 0) {

            item.orderDetailList.forEach(item2 => {
              let goodsSkuJson = item2.hasOwnProperty('goodsSkuJson') && item2.goodsSkuJson ? JSON.parse(item2.goodsSkuJson) : ''
              console.log(goodsSkuJson.skuAttribute);
              if (!['4', '0', null].includes(item2.salesStatus)) {
                return
              }
              tb_arr.push({
                orderCode: item.orderCode,
                createTime: item.createTime,
                memberId: item.memberId,
                buyMemberName: item.buyMemberName,
                skuAttribute: goodsSkuJson ? goodsSkuJson.skuAttribute.map(sku => `${sku.key}:${sku.value}`).join(';') : '',
                goodsName: item2.goodsName,
                orderCount: item2.orderProductCount,
                materialId: item2.materialId,
                orderPriceTotal: (item2.orderPriceTotal / 100).toFixed(2),
                detailDiscountsPrice: (item2.detailDiscountsPrice / 100).toFixed(2),
                detailPayPrice: (item2.detailPayPrice / 100).toFixed(2),
                goodsClassifyName: item2.goodsClassifyName,
                orderRemark: item.orderRemark,
                memberName: item.memberName,
                memberPhone: item.memberPhone,
                memberAddress: item.memberAddress,
                payTime: item.payTime,
                payWay: item.payWay === "Alipay" ? "支付宝" : (item.payWay === "WeChat" ? "微信" : "银行卡")
                // goodsGoTime: item.goodsArrTime,
                // goodsArrTime: item.goodsArrTime
              })
            })
          }
        })
        exportSheetTable({ fileName: '待发货订单', tH_data: th_arr, tB_data: tb_arr, isSheet: true, merge: true, mergeProp: [{ key: 'orderCode' }] })
      }
    } else if (type === 'saleOut') {
      let res = await apiExportLibraryOutReport({ createTimeEnd: (option.hasOwnProperty('time') && option.time.length > 0) ? getDateTime3(option.time[1]) + ' 23:59:59' : '', createTimeStart: (option.hasOwnProperty('time') && option.time.length > 0) ? getDateTime3(option.time[0]) + ' 00:00:00' : '', orderCode: (option.hasOwnProperty('orderCode') && option.orderCode) ? option.orderCode : '' })

      if (res.code === 0 && res.data) {
        let th_arr = [
          {
            title: '序号',
            prop: 'productId'
          },
          {
            title: '日期',
            prop: 'day'
          },
          {
            title: '物料Id',
            prop: 'materialId',
          },
          {
            title: '库存单位',
            prop: 'unit'
          },
          {
            title: '实发数量',
            prop: 'orderProductCount', valueType: 'number'
          },
          {
            title: '含税单价',
            prop: 'orderPrice', valueType: 'number'
          }
        ]
        const tb_arr = res.data
        exportSheetTable({ fileName: '销售出库单', tH_data: th_arr, tB_data: tb_arr, isSheet: true, merge: false, mergeProp: [] })
      }
    }


  }

  printQrCode = () => {
    // this.setState({
    //   printLoading: true
    // }, () => {
    let count = 0
    count = window.prompt('请输入打印数量(1~200之间)：')
    if (!count || count <= 0) return false
    if (!/[0-9]+/.test(count) || count > 200) {
      alert('输入不合法')
      return false
    }
    React.$post('/management/storeInfo/storePrinterName').then(response => {
      const { storeName, QRCodePrinterName } = response.data
      apiIdentificationCodeAdd({ count: count }).then(res => {
        if (res.code == 0) {
          const list = res.data
          printQrCode({ storeName, dataSource: list }, () => {
            this.setState({
              isModalVisible: false,
              printLoading: false
            })
          })
        }
      })
      // axios.get(`http://localhost:8888/admin/bill/printCode/${QRCodePrinterName}/${2000}/${encodeURIComponent(storeName)}`).then(res => {
      //   if (res.code === 0) {
      //     React.$message({
      //       type: 'info',
      //       content: '打印成功'
      //     })
      //   }
      // })
      // this.setState({
      //   isModalVisible: false
      // })
    }).catch(err => {
      this.setState({
        printLoading: false
      })
    })
    // })

  }
  print_logo = () => {
    printLogo()
  }
  showModal = () => {
    this.setState({
      isModalVisible: true
    })
  };
  //
  shopModal = async (orderId) => {
    window.open().location.href = window.location.origin + window.location.pathname + `#/order/mallOrder/details/${orderId}/keeper`
  }
  orderCloseDialog = () => {
    this.setState({
      OrderVisible: false
    })
  }
  handleCancel = () => {
    this.setState({
      isModalVisible: false
    })
  };
  getRowClassName(record, index) {
    if (typeof record !== 'object') return
    let flag = record.orderDetailList.filter(item => !['4', '0', null].includes(item.salesStatus))
    return flag.length > 0 ? "warning" : ''
  }
  openVoice = () => {
    this.setState({
      voiceOn: !this.state.voiceOn
    }, () => {
      let noticeTimer
      if (this.state.voiceOn && this.state.orderState == 4) {
        this.getOrderStatistic()
        noticeTimer = setInterval(() => {
          this.getOrderStatistic()
        }, 10000);
      } else {
        clearInterval(this.state.noticeTimer)
        noticeTimer = null
      }
      this.setState({
        noticeTimer
      })
    })
  }
  billSalePrint = async () => {
    if (this.state.orderList.length === 0) {
      React.$message({
        type: "warning",
        content: '请选择要发货的订单'
      })
      return
    } else {
      let params = {
        orderIds: this.state.orderList.join(','),
      }
      let res = await apiPostMergeOrderDetail(params)
      if (res.code === 0 && res.data) {

        const data = res.data.map(item => {
          let resultData = [], countTotal = 0, payTotal = 0
          item.orderDetailList.forEach((row, index) => {
            row.sort = index + 1
            countTotal += row.orderProductCount
            payTotal += Number(row.orderPriceTotal) ? Number(row.orderPriceTotal) : 0
            row.orderPriceTotal = (row.orderPriceTotal / 100).toFixed(2)
            const goodsSkuJson = row.goodsSkuJson ? JSON.parse(row.goodsSkuJson) : {}
            row.skuStr = goodsSkuJson.skuAttribute.map(sku => {
              return sku.key + ':' + sku.value
            }).join(';')
            row.libraryName = item.libraryName
            row.orderPrice = (row.orderPrice / 100).toFixed(2)
            resultData.push(row)
            if (index === item.orderDetailList.length - 1) {
              resultData.push({
                materialId: '合计',
                orderProductCount: countTotal,
                orderPriceTotal: payTotal ? (payTotal / 100).toFixed(2) : '0'
              })
            }
          })
          return {
            th: [
              { label: '序号', value: 'sort', width: '4%' },
              { label: '物料编码', value: 'materialId', width: '15%' },
              { label: '物料名称', value: 'materialName', width: '30%', align: 'start' },
              { label: '规格型号', value: 'skuStr', width: '9%' },
              { label: '数量', value: 'orderProductCount', width: '4%' },
              { label: '单价', value: 'orderPrice', width: '7%' },
              { label: '金额', value: 'orderPriceTotal', width: '7%' },
              { label: '仓库', value: 'libraryName', width: '7%' },
              { label: '备注', value: 'skuDescription', width: '17%' },
            ],
            title: item.libraryName + '出库单',
            infos: [
              { label: '仓库名称', value: item.libraryName },
              { label: '出库时间', value: item.outLibraryTime },
              { label: '出库单号', value: item.code },
              { label: '对应单号', value: item.orderCode },
              { label: '快递公司', value: res.data.courierName },
              { label: res.data.courierNo ? '快递单号' : '配送员', value: item.courierNo ?? item.deliverymanName },
              { label: '付款时间', value: item.payTime },
              // { label: '备注', value: item.remark }
            ],
            data: resultData,
            remark: item.remark ?? '',
            tfoot: {
              '配货时间': '',
              '发货人': '',
              '复核人': '',
              '审核人': '',
            }
          }
        })
        toPrintTool(data)
        return
        mergePrints(data, true)
      }
    }

  }
  // 配送员列表
  getCourierOptions = async () => {
    let res = await apiDeliverymanPage()
    if (res.code === 0 && res.data) {
      let courierOptions = []
      res.data.map(v => {
        if (v.hasBoundCar) {
          courierOptions.push({
            value: v.deliverymanId,
            label: v.name
          })
        }
      })
      this.setState({ courierOptions })
    }
  }
  render() {
    const { columns, tabData, dataSource, voiceOn, loading, courierOptions, visible, options, lateoptions, logVisible, logisticsInformation, isModalVisible, orderState, columns4, latevisible, mergeVisible, mergeOrder, mergeOrderDataSource, mergeColumns, selectedRowKeys, selectedRows, courierCode, courierNo, OrderVisible, orderDetails, printLoading } = this.state
    const rowSelection = {
      selectedRowKeys,
      fixed: true,
      onChange: this.onChange,
    }
    return (
      <div className='p-layout-box'>

        <div style={{ width: '100%', display: 'flex', justifyContent: 'flex-start', paddingRight: 20, position: 'relative' }}>

          <TheButton hasPermi={['order:MallOrderKeeper:printQrCode']} size="middle" type="default" onClick={this.printQrCode}>打印二维码</TheButton>
          <TheButton hasPermi={['order:MallOrderKeeper:printQrCode']} size="middle" type="default" onClick={this.print_logo} >打印logo</TheButton>
          {orderState == 4 &&
            <Affix style={{ position: 'absolute', top: 0, right: 0 }}>
              <TheButton hasPermi={['order:MallOrderKeeper:voice']} size="middle" type="primary" onClick={this.openVoice}>
                {
                  voiceOn ? '关闭语音提醒' : '开启语音提醒'
                }
              </TheButton></Affix>
          }
        </div>

        {/* <Modal title="打印二维码" visible={isModalVisible} onOk={this.printQrCode} confirmLoading={printLoading} onCancel={this.handleCancel}>
          <p>即将打印200张二维码</p>
        </Modal> */}
        <Tabs activeKey={orderState} onChange={this.changeKey} tabBarExtraContent={<SearchHeader getValue={this.getValue} educeTable={this.educeTable} orderState={orderState} />}>
          {
            tabData.map(v => {
              return <TabPane key={v.key} tab={v.tab}>
                <div className="p-layout-content-pagination">
                  <TheTable loading={loading} scroll={{ x: 'max-content', y: '63vh' }} columns={orderState == 4 ? columns4 : columns} dataSource={dataSource} rowClassName={this.getRowClassName} showTools={true} />
                  <ThePagination
                    pageNo={this.state[`pageData${v.key}`].pageNo}
                    pageSize={this.state[`pageData${v.key}`].pageSize}
                    total={this.state[`total${v.key}`]}
                    pageChange={this.pageChange}
                  />
                </div>
              </TabPane>
            })
          }

        </Tabs>
        <SendGoods options={options} courierOptions={courierOptions} ref={this.sendGoodsRef} refresh={() => this.getData()}></SendGoods>
        {/* <TheDialog
          visible={visible}
          title="发货"
          width={400}
          handleCancel={this.closeDialog}
          footer={null}
        >
          <Form onFinish={this.saveDialog}>
            <Form.Item label="单号" name="courierNo" rules={[{ required: true }]}>
              <Input placeholder='请输入单号' />
            </Form.Item>
            <Form.Item label="快递公司" name="courierCode" rules={[{ required: true }]}>
              <Select allowClear
                options={options}
                showSearch
                filterOption={(input, option) => {
                  return option.label.toUpperCase().includes(input.toUpperCase())
                }
                }
                placeholder='请选择快递公司' />
            </Form.Item>
            <Form.Item>
              <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: -30 }}>
                <Space>
                  <Button onClick={this.closeDialog}>取消</Button>
                  <Button type="primary" htmlType='submit'>确认</Button>
                </Space>
              </div>
            </Form.Item>
          </Form>
        </TheDialog> */}
        <TheDialog
          visible={latevisible}
          title="延迟发货"
          width={400}
          handleCancel={this.latecloseDialog}
          footer={null}
        >
          <Form onFinish={this.saveLateDialog}>
            <Form.Item label="延迟原因" name="delayReason" rules={[{ required: true }]}>
              <Select allowClear
                options={lateoptions}
                showSearch
                filterOption={(input, option) => {
                  return option.label.toUpperCase().includes(input.toUpperCase())
                }
                }
                placeholder='请选择延迟原因' />
            </Form.Item>
            <Form.Item>
              <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: -30 }}>
                <Space>
                  <Button onClick={this.latecloseDialog}>取消</Button>
                  <Button type="primary" htmlType='submit'>确认</Button>
                </Space>
              </div>
            </Form.Item>
          </Form>
        </TheDialog>
        <TheDialog
          visible={logVisible}
          handleCancel={this.logDialogCancel}
          footer={null}
          title={'跟踪物流'}
        >
          <div style={{ height: 500, overflowY: 'auto' }}>
            {
              <>
                快递公司： {courierCode}
                <div>快递单号：{courierNo}</div>
              </>
            }
            {logisticsInformation &&
              <Steps progressDot current={logisticsInformation.length - 1} direction="vertical">
                {logisticsInformation.map(v => {
                  return <Step title={v.time} description={v.desc} />
                })}
              </Steps>}
            {!logisticsInformation && <span>暂无物流信息</span>}
          </div>

          <Space style={{ display: 'flex', justifyContent: 'center', marginTop: 20 }}>
            <Button type={'primary'} onClick={this.logDialogCancel}>确定</Button>
          </Space>
        </TheDialog>
        <TheDialog
          visible={mergeVisible}
          title={<div className='mergeTitle'>选择收货人多个待发货订单，合并发货</div>}
          width={'90%'}
          handleCancel={this.mergeCloseDialog}
          footer={null}
        >
          <div className='msgTitle'>
            收货人信息
            <Button
              style={{ marginRight: 12, float: 'right' }}
              type="default"
              onClick={this.billSalePrint} >
              出库单打印
            </Button>
          </div>
          <div className='msgContent' >
            <>
              {/* <Row>
                <Col span={3}>
                  <div>
                    用户昵称
                  </div>
                </Col>
                <Col span={20}>
                  {mergeOrder.buyMemberName}
                </Col>
              </Row> */}
              <Row>
                <Col span={3}>
                  <div>
                    收货人
                  </div>
                </Col>
                <Col span={20}>
                  {mergeOrder.memberName}
                </Col>
              </Row>
              <Row>
                <Col span={3}>
                  <div>
                    联系方式
                  </div>
                </Col>
                <Col span={20}>
                  {mergeOrder.memberPhone}
                </Col>
              </Row>
              <Row>
                <Col span={3}>
                  <div>
                    收货地址
                  </div>
                </Col>
                <Col span={20}>
                  {mergeOrder.memberAddress}
                </Col>
              </Row>
            </>
          </div>
          <div className='msgTitle'>
            待发货订单
          </div>
          <div className='readyOrder'>
            <Row >
              <Col span={12}>
                <div style={{ outline: "1px solid gainsboro" }}>
                  <div className='ordertitle'>
                    <div style={{ outline: "1px solid gainsboro", height: "40px", lineHeight: "40px", textIndent: "24px" }}>
                      待发订单
                    </div>
                  </div>
                  <div className='orderlist'>
                    <TheTable
                      scroll={{ x: 'max-content', y: 215 }}
                      columns={mergeColumns}
                      dataSource={mergeOrderDataSource}
                      rowKey={record => record.shopOrderId}
                      rowSelection={rowSelection}
                    />
                  </div>
                </div>
              </Col>
              <Col span={12}>
                <div>
                  <div className='ordertitle'>
                    <div style={{ outline: "1px solid gainsboro", height: "40px", lineHeight: "40px", textIndent: "24px" }}>
                      已选择的订单
                    </div>
                  </div>
                  <div className='orderlist' style={{ overflowY: "scroll" }}>
                    <div style={{ padding: "10px", width: "100%", height: "270px" }} >
                      <List
                        dataSource={selectedRows}
                        itemLayout="horizontal"
                        renderItem={(item) => (
                          <List.Item>
                            <Col span={8}>
                              订单编号  {item.orderCode}
                            </Col>
                            {/* <Col span={15}>
                              商品名称  {item.orderDetailList[0].goodsName}
                            </Col> */}
                            <div onClick={() => this.CancelChange(item.shopOrderId, item)}>
                              <CloseOutlined
                                style={{ fontSize: "20px", color: "red" }}
                              />
                            </div>

                          </List.Item>)}
                      />
                    </div>
                  </div>
                </div>
              </Col>
            </Row>
          </div>
          <div className='msgTitle'>
            快递信息
          </div>
          <div className='msgContent'>
            <Form
              ref={this.mergeformRef}
              labelAlign="left"
              labelCol={{ span: 2 }}
              wrapperCol={{ span: 4 }}
            >
              <Form.Item label="单号" name="courierNo" rules={[{ required: true }]}>
                <Input placeholder='请输入单号' />
              </Form.Item>
              <Form.Item label="快递公司" name="courierCode" rules={[{ required: true }]}>
                <Select allowClear
                  options={
                    options.filter((v) => { return v.value !== 'HQM' })
                  }
                  showSearch
                  filterOption={(input, option) => {
                    return option.label.toUpperCase().includes(input.toUpperCase())
                  }
                  }
                  placeholder='请选择快递公司' />
              </Form.Item>
            </Form>
          </div>
          <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 10, marginBottom: 20 }}>
            <Space>
              <Button onClick={this.mergeCloseDialog}>取消</Button>
              <Button type="primary" onClick={this.mergeSaveDialog}>合并发货</Button>
            </Space>
          </div>
        </TheDialog>
        <TheDialog visible={OrderVisible}
          title={<div className='mergeTitle'>订单详情</div>}
          width={'60%'}
          handleCancel={this.orderCloseDialog}
          footer={null}>
          <List
            dataSource={orderDetails}
            itemLayout="horizontal"
            renderItem={(item) => (
              <List.Item>
                <Col span={6}>
                  商品名称：{item.goodsName}
                </Col>
                <Col span={4}>
                  <TheImage src={item.goodsImage} width={80} height={80} />
                </Col>
                {/* <Col span={6}>
                  商品物料名称：{item.materialName}
                </Col> */}
                <Col span={4}>
                  物料ID：{item.materialId}
                </Col>
                <Col span={2}>
                  单价：<React.$Price price={item.orderPrice} />
                </Col>
                <Col span={2}>
                  数量：{item.orderProductCount}
                </Col>
              </List.Item>)
            }
          />
        </TheDialog>
      </div>
    )
  }
}
